使用python製作簡易OpenCV影像辨識的小實作,有提供Pycharm及Spyder的opencv庫安裝方式,後續將實作Androidstudio安卓系統與OpenCV結合的APP,以下言論純個人分享,如有大神能建議及改善的地方非常歡迎留言!!!
開發流程:
使用Pycharm、Spyder安裝OpenCV庫
pip install numpy
pip install opencv-python
pip uninstall numpy
pip uninstall opencv-python
pip install numpy
pip install opencv-python
開始實作前須先了解OpenCV圖像處理
import cv2
import numpy as np
import cv2
img = cv2.imread("E:/2024_NTNU/Python/NN.JPG")
img = cv2.resize(img, (700, 500))
cv2.imshow("image1", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
imread:讀取圖片位置("X:/../../../XX.JPG")
resize:將圖片轉成自己調整的大小(寬,高)
imshow:顯示圖片("image1"標題框, img定義的圖片名變數)
waitKey:無限等待時間,這個沒打圖片會消失or當機
cv2.destroyWindows(Windows_name):刪除單一指定影像視窗
cv2.destroyAllWindows():刪除所有Open Cv影像視窗
import cv2
img = cv2.imread("E:/2024_NTNU/Python/NN.JPG")
img = cv2.resize(img, (700, 500))
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("image1", gray_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
gray_img為灰階後的圖片
二值化(Threshold)binary_img = cv2.threshold(gray_img, 128, 255, cv2.THRESH_BINARY)[1]
使用threshold會返回兩個值,[0]是原本的灰階後圖片,[1]是二值化後的圖片
也可以寫成_, binary_img = cv2.threshold(gray_img, 128, 255, cv2.THRESH_BINARY)
記得底下cv2.imshow("image1", img)的img改成你定義的圖片
Canny邊緣化
import cv2
img = cv2.imread("E:/2024_NTNU/Python/NN.JPG")
img = cv2.resize(img, (700, 500))
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
canny_img = cv2.Canny(gray_img, 60, 0)
cv2.imshow("image1", canny_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
圖片邊緣=與周圍像素質差很大(圖片,最低門檻值(200以下過濾),最高門檻值(超過當邊緣))
可以自行設定閥值
import numpy as np
矩陣運算import cv2
import numpy as np
kernel = np.ones((5, 5), np.uint8)
img = cv2.imread("E:/2024_NTNU/Python/NN.JPG")
img = cv2.resize(img, (700, 500))
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
canny_img = cv2.Canny(gray_img, 60, 0)
dilate = cv2.dilate(canny_img, kernel, iterations=1)
cv2.imshow("image1", dilate)
cv2.waitKey(0)
cv2.destroyAllWindows()
kernel = np.ones((5, 5), np.uint8)
使用創建NumPy庫中的np.ones創建一個5*5正方形結構(5行5列)dilate = cv2.dilate(canny_img, kernel, iterations=1)
膨脹效果=邊緣線條變粗(圖片,2微陣列的和(np),膨脹次數)
eroded_img = cv2.erode(canny_img, kernel, iterations=0)
dilate = cv2.dilate(canny_img, kernel, iterations=1)
eroded_img = cv2.erode(dilate, kernel, iterations=2)